import React from 'react';
import { Form as AntForm, Button } from 'antd';
import type { FormProps as AntFormProps } from 'antd/es/form';

const { Item } = AntForm;

export interface FormField {
  name: string;
  label: string;
  type: 'input' | 'select' | 'checkbox' | 'radio' | 'datepicker' | 'custom';
  required?: boolean;
  rules?: Record<string, unknown>[];
  component?: React.ReactNode;
  props?: Record<string, unknown>;
}

export interface CustomFormProps extends AntFormProps {
  componentId?: string;
  fields?: FormField[];
  showSubmitButton?: boolean;
  submitText?: string;
  showResetButton?: boolean;
  resetText?: string;
  onFinish?: (values: Record<string, unknown>) => void;
}

const Form: React.FC<CustomFormProps> = ({
  componentId,
  fields = [],
  showSubmitButton = true,
  submitText = '提交',
  showResetButton = true,
  resetText = '重置',
  onFinish,
  children,
  ...props
}) => {
  const [form] = AntForm.useForm(props.form);

  const handleReset = () => {
    form.resetFields();
  };

  return (
    <AntForm
      form={form}
      onFinish={onFinish}
      layout="vertical"
      {...props}
      data-component-id={componentId}
    >
      {fields.map((field) => (
        <Item
          key={field.name}
          name={field.name}
          label={field.label}
          rules={field.required ? [{ required: true, message: `请输入${field.label}` }, ...(field.rules || [])] : field.rules}
        >
          {field.component || null}
        </Item>
      ))}
      
      {children}
      
      {(showSubmitButton || showResetButton) && (
        <Item>
          <div style={{ display: 'flex', gap: '8px' }}>
            {showSubmitButton && (
              <Button type="primary" htmlType="submit">
                {submitText}
              </Button>
            )}
            {showResetButton && (
              <Button onClick={handleReset}>
                {resetText}
              </Button>
            )}
          </div>
        </Item>
      )}
    </AntForm>
  );
};

export default Form; 